import org.imgscalr.Scalr;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;

import java.awt.image.BufferedImage;

import java.io.File;
import java.io.IOException;

import java.util.Iterator;
import java.util.List;

public class ImageResizerThread extends Thread {
    private List<File> files;
    private String dstFolder;
    private int newWidth;

    public ImageResizerThread(List<File> files, String dstFolder, int newWidth) {
        this.files = files;
        this.dstFolder = dstFolder;
        this.newWidth = newWidth;
    }

    public void run() {
        try {
            while (true) {
                File file = files.remove(0);
                resize(file);
            }
        } catch (IndexOutOfBoundsException e) {
            // Regular end of file list
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void resize(File file) throws IOException {
        if (!file.isFile()) {
            return;
        }

        ImageInputStream stream = new FileImageInputStream(file);
        Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);
        if (!readers.hasNext()) {
            // Unknown file format
            return;
        }

        String format = readers.next().getFormatName();

        BufferedImage image = null;
        try {
            image = ImageIO.read(stream);
        } catch (IOException ignored) {}

        if (image == null) {
            // File can't be read or broken image file
            return;
        }

        int newHeight = (int) Math.round(
            image.getHeight() / (image.getWidth() / (double) newWidth)
        );

        BufferedImage newImage = Scalr.resize(image, newWidth, newHeight);

        File newFile = new File(dstFolder + "/" + file.getName());
        ImageIO.write(newImage, format, newFile);
    }
}
